<?php
// +----------------------------------------------------------------------
// | Fanwe 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.fanwe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 云淡风轻(97139915@qq.com)
// +----------------------------------------------------------------------

//会员
class UserAction extends CommonAction{
	public function index()
	{
		$user_name = trim($_REQUEST['user_name']);
		$email = trim($_REQUEST['email']);
		$group_id = intval($_REQUEST['group_id']);
		$status = trim($_REQUEST['status']);
		
		if(!empty($user_name))
		{
			$this->assign("user_name",$user_name);
			$where.=" and u.user_name like '%$user_name%'";
			$parameter .= "user_name=" . urlencode($user_name)."&";
		}
		
		if(!empty($email))
		{
			$this->assign("email",$email);
			$where.=" and u.email like '%$email%'";
			$parameter .= "email=" . urlencode($email)."&";
		}
		
		if(!empty($group_id))
		{
			$this->assign("group_id",$group_id);
			$where.=" and u.group_id = $group_id";
			$parameter .= "group_id=" . $group_id."&";
		}
		
		if($status != "" && $status >= 0)
		{
			$where.=" and u.status = $status";
			$parameter .= "status=" . $status ."&";
			$this->assign("status",$status);
		}
		else
		{
			$this->assign("status",-1);
		}
		
		$sql_str = 'SELECT u.*,ug.name as group_name '.
					'FROM '.C("DB_PREFIX").'user as u '.
					'left join '.C("DB_PREFIX").'user_group as ug on ug.id = u.group_id '.
					"where u.id is not null $where group by u.id";
		
		$model = M();
        $voList = $this->_Sql_list($model, $sql_str, "&".$parameter, 'id', false);
		
		$user_group = D("UserGroup")->where("status=1")->order("id asc")->findAll();
		$this->assign("user_group",$user_group);
		
		$this->display ();
		return;
	}
	
	public function add() {
		$default_lang_id = D("LangConf")->where("lang_name='".C('DEFAULT_LANG')."'")->field("id")->find();
		$default_lang_id = $default_lang_id['id'];  //默认语言的ID
		$this->assign("group_list",D("UserGroup")->where("status=1")->order("id asc")->findAll());
		$this->assign("city_list",D("GroupCity")->where("status=1")->findAll());
		$this->display ();
	}
	function insert()
	{
		$validate  = array(
			array('user_name','require',L('NAME_REQUIRE')),
			array('user_name','',L('NAME_EXISTS'),0,'unique',1),
			array('email','require',L('EMAIL_REQUIRE')),
			array('email','email',L('EMAIL_ERROR')),
			array('email','',L('EMAIL_EXISTS'),0,'unique',1),
			array('user_pwd','require',L('PASSWORD_REQUIRE')),
			array('user_pwd','user_pwd_confirm',L('COMFIRM_PASSWORD_ERROR'),0,'confirm'),
		);
		
		$data['rec_id'] = trim($_POST['rec_id']);
		$data['user_name'] = trim($_POST['user_name']);
		$data['tel'] = trim($_POST['tel']);
		$data['email'] = trim($_POST['email']);
		$data['user_pwd'] = $_POST['user_pwd'];
		$data['user_pwd_confirm'] = $_POST['user_pwd_confirm'];
		$data['qq_msn'] = trim($_POST['qq_msn']);
		$data['contact'] = trim($_POST['contact']);
		$data['group_id'] = intval($_POST['group_id']);
		$data['city_id'] = intval($_POST['city_id']);
		if ($data['group_id'] == 2) 
			$data['group_type'] = 'Site';
		else
			$data['group_type'] = 'User';
		$data['status'] = 1;
		$data['create_time'] = gmtTime();
		$data['update_time'] = gmtTime();
		$user = D("User");
		$user -> setProperty("_validate",$validate);
		$result = $user->create($data);
		
		if($result)
		{
			$code = fanweC('INTEGRATE_CODE');
			if (empty($code))
				$code = 'fanwe';
			
			if($code != 'fanwe')
			{
				$users = &init_users();
				$is_add = $users->add_user($data['user_name'],$data['user_pwd'],$data['email']);
				if(!$is_add)
				{
					// 插入会员数据失败 
					if ($users->error == 'register_user_name_range')
					{
						$msg = '无效的用户名';
					}
					elseif ($users->error == 'register_user_name_not_allow')
					{
						$msg = '用户名不允许注册';
					}
					elseif ($users->error == 'register_user_name_exist')
					{
						$msg = '已经存在一个相同的用户名。';
					}
					elseif ($users->error == 'register_email_error')
					{
						$msg = '无效的email地址';
					}
					elseif ($users->error == 'register_email_not_allow')
					{
						$msg = '邮件帐号不允许';
					}
					elseif ($users->error == 'register_email_exist')
					{
						$msg = '该邮件帐号已经存在。';
					}
					else
					{
						$msg = $users->error_msg();
					}
					$this->error ($msg);
				}
				else
				{
					$uc_arr = $users->get_profile_by_name($data['user_name']);
					$data['ucenter_id'] = $uc_arr['id'];	
				}
			}
			
			$data['user_pwd'] = md5($data['user_pwd']);
			$user -> setProperty("data",$data);
			$user_id = $user->add();
			
			$msg = "添加会员".$_REQUEST['user_name'];
			$this->saveLog(1,$user_id,$msg);
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('ADD_SUCCESS'));
		}
		else
		{
			$msg = "添加会员".$_REQUEST['user_name'];
			$this->saveLog(0,0,$msg);
			$this->error (L('ADD_FAILED'));
		}
	}

	public function edit()
	{
		$this->assign("group_list",D("UserGroup")->findAll());
		
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		
		D('User')->syncUserScore($id);
		
		$vo = $model->getById ( $id );
		$this->assign ( 'vo', $vo );
		$this->assign("site",D("Site")->where("id = $vo[rec_id]")->find());
		$this->assign("city_list",D("GroupCity")->where("status=1")->findAll());
		$this->display ();
	}
	
	function update()
	{
		//B('FilterString');
		$new_user_pwd = $_REQUEST['new_user_pwd'];
		$new_score = intval($_REQUEST['score']);
		$id = intval($_REQUEST['id']);
		$name=$this->getActionName();
		$model = D ( $name );
		$data = $model->create();
		if (false === $data) {
			$this->error ( $model->getError () );
		}
		
		D('User')->syncUserScore($id);
		$o_data = D("User")->getById($id);  //原来的用户数据
		
		if($new_user_pwd != "")
			$data['user_pwd'] = md5($new_user_pwd);
		else
			unset($data['user_pwd']);
			
		$code = fanweC('INTEGRATE_CODE');
		if (empty($code))
			$code = 'fanwe';
		
		if($code != 'fanwe')
		{
			$users = &init_users();
			
			if($new_user_pwd != "")
			{
				$cfg['email'] = '';
				$cfg['username'] = $o_data['user_name']; 
				$cfg['password'] = $new_user_pwd;
				$is_edit = $users->edit_user($cfg);
				if(!$is_edit)
				{
					$msg = L('EDIT_FAILED');
					$this->saveLog(0,0,"修改会员".$o_data['user_name']);
					$this->error($msg);
				}
			}
			
			if($new_score != $o_data['score'])
			{
				$add_score = $new_score - intval($o_data['score']);
				$ucenter_id = $o_data["ucenter_id"];
				$users->update_credit($ucenter_id,$add_score);
			}
		}
    		
		if ($data['group_id'] == 2) 
			$data['group_type'] = 'Site';
		else 
			$data['group_type'] = 'User';
				    
		$list=$model->save ($data);
		if (false !== $list) {
			$msg = "修改会员".$o_data['user_name'];
			$this->saveLog(1,$list,$msg);
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		} else {
			//错误提示
			$msg = "修改会员".$o_data['user_name'];
			$this->saveLog(0,0,$msg);
			$this->error (L('EDIT_FAILED'));
		}
	}
	
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			$ids = explode ( ',', $id );
			$names = '';
			$uids = '';
			$users  = &init_users();
			$users->need_sync = false;
			foreach($ids as $idd)
			{
				$names .= ','.M("User")->where("id=".$idd)->getField("user_name");
				$uids .= ','.M("User")->where("id=".$idd)->getField("ucenter_id");
			}
			if($names!='')
			{
				$names = substr($names,1);
				$uids = substr($uids,1);
			}
			
			if(isset ($id))
			{				
				$condition = array ($pk => array ('in', explode ( ',', $id )));
				
				$code = fanweC('INTEGRATE_CODE');
				if (empty($code))
					$code = 'fanwe';
				
				if($code != 'fanwe')
				{
					$users = &init_users();
					$is_delete = $users->remove_user_by_ids($uids);
				}
				else
					$is_delete = true;
				
				if ($is_delete && (false !== $model->where ( $condition )->delete ()))
				{
					
					//删除会员将永久删除相关的一切留言，回复，订单，订单商品等数据，请谨慎操作
					//删除相关会员留言
					$msglist = D("Message")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->findAll();
					D("Message")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					foreach($msglist as $item)
					{
						D("Message")->where("pid=".$item['id'])->delete();
					}
					//删除订单及商品
					D("Order")->where( array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					
					//删除会员的收货人列表
					D("UserConsignee")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					
					//删除相关会员的资金与积分日志
					M("UserIncharge")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					M("UserScoreLog")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					
					M("UserCollect")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					M("UserGoods")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					M("UserSite")->where(array ("user_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					
					$msg = "删除会员:".$names;
					$this->saveLog(1,0,$msg);
					$this->success (L('DEL_SUCCESS'));
				} else {
					$msg = "删除会员:".$names;
					$this->saveLog(0,0,$msg);
					$this->error (L('DEL_FAILED'));
				}
			} else {
				$msg = "删除会员:".$names;
				$this->saveLog(0,0,$msg);
				$this->error ( L('INVALID_OP') );
			}
		}
		$this->forward ();
	}
	
	public function forbid() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		$list=$model->forbid ( $condition );
		$name = $model->where("id=".$id)->getField("user_name");
		if ($list!==false) {	
			$msg = "禁用会员：".$name;		
			$this->saveLog(1,$id,$msg);
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( L('FORBID_SUCCESS') );
		} else {
			$msg = "禁用会员：".$name;		
			$this->saveLog(0,0,$msg);
			$this->error  (  L('FORBID_FAILED') );
		}
	}
	
	public function resume() {
		//恢复指定记录
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		$name = $model->where("id=".$id)->getField("user_name");
		if (false !== $model->resume ( $condition )) {
			$msg = "恢复会员：".$name;		
			$this->saveLog(1,$id,$msg);
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( L('RESUME_SUCCESS') );
		} else {
			$msg = "恢复会员：".$name;		
			$this->saveLog(0,0,$msg);
			$this->error ( L('RESUME_FAILED') );
		}
	}
	
	public function getUserList()
	{
		$key = trim($_REQUEST['key']);
		$is_site = intval($_REQUEST['is_site']);
		
		$where = "u.status = 1";
		
		if($is_site == 1)
			$where.=" and u.group_id = 2";
		
		if(!empty($key))
			$where.=" and u.user_name like '%$key%'";
		
		$sql = 'SELECT u.id,u.user_name '.
					'FROM '.C("DB_PREFIX").'user as u '.
					"where $where order by u.id desc limit 0,30";
		
		$userList = M()->query($sql);
		
		echo json_encode($userList);
	}
}
?>